package com.zhoutao123.hephaestus.controller;

import com.zhoutao123.hephaestus.object.bussiness.VSysResources;
import com.zhoutao123.hephaestus.object.bussiness.VUploadResult;
import com.zhoutao123.hephaestus.object.transport.PageBean;
import com.zhoutao123.hephaestus.service.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Api(description = "资源-文件上传")
public class UploadResource {

    @Autowired
    private UploadService uploadService;

    @PostMapping("/upload")
    @ApiOperation(
            value = "文件上传接口",
            notes = "图片资源上传接口,暂未添加资源过滤配置,文件名更改为：`时间戳 + 原文件名` \n + 上传文件最大支持 10M ,大于10M将上传失败")
    public VUploadResult uploadImgQiniu(MultipartFile multipartFile) throws IOException {
        String oldFileName = multipartFile.getOriginalFilename();
        String fileName = System.currentTimeMillis() + "-" + oldFileName;
        FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
        String path = uploadService.uploadFileToQiNiuCloud(inputStream, fileName);
        // 写入资源数据库
        uploadService.saveUploadFileRecord(oldFileName, path, (int) (multipartFile.getSize() / 1024));
        return new VUploadResult().setPath(path).setFileName(oldFileName);
    }

    @GetMapping
    @ApiOperation("获取文件上传记录信息")
    public VSysResources getFileList(PageBean pageBean) {
        return uploadService.getFileList(pageBean);
    }
}
